package com.mocha.bss.domain.rbac.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coffee.core.CoffeeException;
import com.mocha.bss.config.BssResponseEnum;
import com.mocha.bss.domain.org.repository.entity.UserEntity;
import com.mocha.bss.domain.rbac.repository.entity.RoleEntity;
import com.mocha.bss.domain.rbac.repository.mapper.MochaRoleMapper;
import com.mocha.bss.rbac.bo.RoleBO;
import com.pinghua.mocha.basics.NumberKits;
import com.pinghua.mocha.basics.dmo.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author songkui
 * @since 2022-03-11
 */
@Service
@Slf4j
public class MochaRoleRepository extends ServiceImpl<MochaRoleMapper, RoleEntity>  {

    public List<RoleEntity> findRolesByUserId(long userId){
        return super.baseMapper.findRolesByUserId(userId);
    }

    public List<RoleEntity> findRolesByAll(){
        return list();
    }

    public void saveRole(RoleBO roleBO) {
        if (isExist(roleBO)){
            throw new CoffeeException(BssResponseEnum.RoleExist);
        }
        RoleEntity roleEntity = BeanUtil.copyProperties(roleBO, RoleEntity.class);
        save(roleEntity);
    }

    public void updateRole(RoleBO roleBO) {
        if (isExist(roleBO)){
            throw new CoffeeException(BssResponseEnum.RoleExist);
        }
        RoleEntity roleEntity = BeanUtil.copyProperties(roleBO, RoleEntity.class);
        updateById(roleEntity);
    }

    private boolean isExist(RoleBO roleBO) {
        List<RoleEntity> list = this.lambdaQuery().select(RoleEntity::getId)
                .eq(RoleEntity::getRoleCode, roleBO.getRoleCode())
                .or().eq(RoleEntity::getRoleName, roleBO.getRoleName()).list();

        if (CollectionUtil.isEmpty(list)){
            return false;
        }
        log.info("is Exist：list: {}", ArrayUtil.join(list.stream().map(RoleEntity::getId).toArray(), ","));
        RoleEntity entity = list.get(0);
        if (NumberKits.isMinus(roleBO.getId())){
            return true;
        }
        return !roleBO.getId().equals(entity.getId());
    }

    public List<RoleVO> listByQuery(RoleBO roleBO) {
        LambdaQueryWrapper<RoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(roleBO.getRoleCode()),RoleEntity::getRoleCode, roleBO.getRoleCode())
                .like(StrUtil.isNotBlank(roleBO.getRoleName()),RoleEntity::getRoleName, roleBO.getRoleName());
        List<RoleEntity> roleEntities = getBaseMapper().selectList(wrapper);
        List<RoleVO> roleVOS = BeanUtil.copyToList(roleEntities, RoleVO.class);
        return roleVOS;
    }
}

